import { sys, log } from "cc";

/**
 * 数据中心
 */
export class DataManager {

    private _local: Storage | null = sys.localStorage;
    private _data: Map<string, any> = new Map();

    /**
     * 数据中心初始化
     */
    static init(_jees: any) {
        _jees.D = new DataManager();
    }

    public constructor() {
        this.loadData();
        this.getCapacity();
    }

    /**
     * 数据加载进本地 _data 中
     */
    loadData() {
        let local_len: number = this._local?.length || 0;
        if (local_len > 0) {
            for (let i = 0; i < local_len; i++) {
                let local_key = this._local?.key(i);
                if (local_key) {
                    let local_one = this.get(local_key, true);
                    if (typeof local_one === 'object') {
                        this._data.set(local_key, JSON.stringify(local_one));
                    } else {
                        this._data.set(local_key, local_one);
                    }
                }
            }
        }
    }

    /**
     * 将数据设置进 LocalStorate 和 本地 Map 中
     * @param {String} _key 
     * @param {String} _val 
    */
    public set(_key: string, _val: any) {
        this._local?.setItem(_key, _val);
        this._data.set(_key, _val);
    }

    /**
     * 获取数据
     * @param {String} _key 键值
     * @param {Boolean} _json 是否将 json 格式字符串转为 json 对象
     */
    public get(_key: string, _json?: boolean): any {
        let data: string | object | null | undefined = null;
        if (this._data.has(_key)) data = this._data.get(_key);
        else data = this._local?.getItem(_key);
        if (_json === true) {
            if (typeof data === 'string') {
                try { data = JSON.parse(data); } catch (e) { }
            }
        }
        return data;
    }

    /**
     * 移除数据
     * @param {String} _key 键值
     */
    public del(_key: string) {
        this._data.delete(_key);
        return this._local?.removeItem(_key);
    }

    /**
     * 查看本地存储容量(单位:KB)
     * @returns 大小
     */
    public getCapacity() {
        let size = 0;
        for (let item in this._local) {
            if (this._local.hasOwnProperty(item)) {
                let data = this._local.getItem(item);
                size += data ? data.length : 0;
            }
        }
        let size_show = ((size / 1024).toFixed(2)) + "KB";
        log("已使用存储：", size_show);
        return size_show;
    }

    /**
     * 打印本地存储数据
     */
    public printStorage() {
        for (let key in this._local) {
            if (this._local.hasOwnProperty(key)) {
                let data = this._local.getItem(key);
                log(`${key}: ${data}`);
            }
        }
    }

    /**
     * 打印本地 Map 数据
     */
    public printData() {
        for (let key of this._data.keys()) {
            let data = this._data.get(key);
            log(`${key}: ${data}`);
        }    
    }

}